<h2>Why is this an issue?</h2>
<p>A <code>for</code> loop with a counter moving away from the end of the specified range is likely a programming mistake.</p>
<p>If the intention is to iterate over the specified range, this differs from what the loop does because the counter moves in the wrong direction.</p>
<p>If the intention is to have an infinite loop or a loop terminated only by a break statement, there are two problems:</p>
<ol>
  <li> The loop condition is not infinite because the counter variable will eventually overflow and fulfill the condition. This can take a long time,
  depending on the data type of the counter. </li>
  <li> An infinite loop terminated by a <code>break</code> statement should be implemented using a <code>while</code> or <code>do</code>
  <code>while</code> loop to make the developer’s intention clear to the reader. </li>
</ol>
<h2>How to fix it</h2>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<p>Change the direction of the counter.</p>
<pre data-diff-id="1" data-diff-type="noncompliant">
for (int i = 10; i &gt; 0; i++) { // Noncompliant, wrong direction
  System.out.println("Hello, world!") // executed ca. 2 billion times
}
</pre>
<pre data-diff-id="2" data-diff-type="noncompliant">
public void doSomething(String [] strings) {
  for (int i = 0; i &lt; strings.length; i--) { // Noncompliant, wrong direction
    String string = strings[i];  // ArrayIndexOutOfBoundsException when i reaches -1
    // ...
  }
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
for (int i = 10; i &gt; 0; i--) { // Compliant
  System.out.println("Hello, world!") // executed 10 times
}
</pre>
<pre data-diff-id="2" data-diff-type="compliant">
public void doSomething(String [] strings) {
  for (int i = 0; i &lt; strings.length; i++) { // Compliant
    String string = strings[i];
    // ...
  }
}
</pre>
<h4>Noncompliant code example</h4>
<p>If the intention is to have an infinite loop or a loop terminated only by a break statement, use a <code>while</code> or a <code>do</code>
<code>while</code> statement instead.</p>
<pre data-diff-id="3" data-diff-type="noncompliant">
for (int i = 0; i &lt; 0; i++) { // Noncompliant, loop is not infinite
  String event = waitForNextEvent();
  if (event == "terminate") break;
  processEvent(event);
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="3" data-diff-type="compliant">
while (true) { // Compliant
  String event = waitForNextEvent();
  if (event == "terminate") break;
  processEvent(event);
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
  <li> <a href="https://wiki.sei.cmu.edu/confluence/x/aTdGBQ">CERT, MSC54-J.</a> - Avoid inadvertent wrapping of loop counters </li>
</ul>
<h3>Articles &amp; blog posts</h3>
<ul>
  <li> <a href="https://en.wikipedia.org/wiki/Integer_overflow">Wikipedia - Integer overflow</a> </li>
</ul>

